//
//  SecureTextEntryView.m
//  SecureTextEntryView
//
//  Created by 杨林杰 on 2019/5/18.
//  Copyright © 2019 YLJ. All rights reserved.
//

#import "SecureTextEntryView.h"
@class SecureTextEntryViewConfig;

@interface SecureTextEntryView ()

@property (nonatomic, strong) SecureTextEntryViewConfig *config;

@property (nonatomic, strong)NSMutableString *text;

@property (nonatomic, getter=isShow) BOOL show;
@end

@implementation SecureTextEntryView

// MARK: 外部调用方法
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.text = [NSMutableString string];
        self.backgroundColor = self.config.backgroundColor;
    }
    return self;
}

- (void)updateConfig:(void (^)(SecureTextEntryViewConfig * _Nonnull))configBlock {
    if (configBlock) {
        configBlock(self.config);
    }
    self.backgroundColor = self.config.backgroundColor;
    [self setNeedsDisplay];
}
- (void)reset {
    self.text = [NSMutableString stringWithString:@""];
    if ([self.delegate respondsToSelector:@selector(secureTextEntryDidChange:)]) {
        [self.delegate secureTextEntryDidChange:self];
    }
    if ([self.delegate respondsToSelector:@selector(secureTextEntryDidDelete:)]) {
        [self.delegate secureTextEntryDidDelete:self];
    }
    [self setNeedsDisplay];
}
// MARK: 重写内部方法
- (UIKeyboardType)keyboardType {
    return UIKeyboardTypeNumberPad;
}

- (BOOL)becomeFirstResponder {
    if (!self.isShow) {
        if ([self.delegate respondsToSelector:@selector(secureTextEntryBegin:)]) {
            [self.delegate secureTextEntryBegin:self];
        }
    }
    self.show = YES;
    return [super becomeFirstResponder];
}

- (BOOL)resignFirstResponder {
    if (self.isShow) {
        if ([self.delegate respondsToSelector:@selector(secureTextEntryEnd:)]) {
            [self.delegate secureTextEntryEnd:self];
        }
    }
    self.show = NO;
    return [super resignFirstResponder];
}

- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (BOOL)canResignFirstResponder {
    return YES;
}

- (BOOL)isSecureTextEntry {
    return !self.config.isThreePartyKeyboard;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (![self isFirstResponder]) {
        [self becomeFirstResponder];
    }
}

// MARK: UIKeyInput
- (BOOL)hasText {
    return self.text.length > 0;
}

- (void)insertText:(NSString *)text {
    if (self.text.length < self.config.count) {
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
        NSString *filtered = [[text componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        BOOL basicTest = [text isEqualToString:filtered];
        if (basicTest) {
            [self.text appendString:text];
            if ([self.delegate respondsToSelector:@selector(secureTextEntryDidChange:)]) {
                [self.delegate secureTextEntryDidChange:self];
            }
            if (self.text.length == self.config.count) {
                if ([self.delegate respondsToSelector:@selector(secureTextEntryComplete:)]) {
                    [self.delegate secureTextEntryComplete:self];
                }
            }
            [self setNeedsDisplay];
        }
    }
}

- (void)deleteBackward {
    if (self.text.length > 0) {
        [self.text deleteCharactersInRange:NSMakeRange(self.text.length - 1, 1)];
        if ([self.delegate respondsToSelector:@selector(secureTextEntryDidChange:)]) {
            [self.delegate secureTextEntryDidChange:self];
        }
        if ([self.delegate respondsToSelector:@selector(secureTextEntryDidDelete:)]) {
            [self.delegate secureTextEntryDidDelete:self];
        }
        [self setNeedsDisplay];
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    CGFloat height = rect.size.height;
    CGFloat width = rect.size.width;
    CGFloat squareWidth = MIN(MAX(MIN(height, self.config.inputWidth), self.config.radius * 4), height);
    CGFloat radius = MIN(self.config.radius, squareWidth * 0.5) * 0.8;
    CGFloat middleSpace = (width - self.config.count * squareWidth) / (self.config.count - 1 + self.config.multiple * 2);
    CGFloat leftSpace = middleSpace * self.config.multiple;
    CGFloat y = (height - squareWidth) * 0.5;
    CGContextRef context = UIGraphicsGetCurrentContext();
    //画外框
    for (NSUInteger i = 0; i < self.config.count; i++) {
        CGContextAddRect(context, CGRectMake(leftSpace + i * squareWidth + i * middleSpace, y, squareWidth, squareWidth));
        CGContextSetLineWidth(context, 1);
        CGContextSetStrokeColorWithColor(context, self.config.borderColor.CGColor);
        CGContextSetFillColorWithColor(context, self.config.inputBackgroundColor.CGColor);
    }
    CGContextDrawPath(context, kCGPathFillStroke);
    CGContextSetFillColorWithColor(context, self.config.pointColor.CGColor);
    //画黑点
    for (NSUInteger i = 1; i <= self.text.length; i++) {
        CGContextAddArc(context,  leftSpace + i * squareWidth + (i - 1) * middleSpace - squareWidth * 0.5, y + squareWidth * 0.5, radius, 0, M_PI * 2, YES);
        CGContextDrawPath(context, kCGPathFill);
    }
}

// MARK: 初始化
- (SecureTextEntryViewConfig *)config {
    if (_config == nil) {
        _config = [SecureTextEntryViewConfig defaultConfig];
    }
    return _config;
}

@end

@implementation SecureTextEntryViewConfig

+ (instancetype)defaultConfig {
    SecureTextEntryViewConfig *config = [[SecureTextEntryViewConfig alloc] init];
    config.inputWidth = 50;
    config.count = 6;
    config.radius = 18 * 0.5;
    config.multiple = 5;
    config.borderColor = [UIColor lightGrayColor];
    config.pointColor = [UIColor blackColor];
    config.inputBackgroundColor = [UIColor whiteColor];
    config.backgroundColor = [UIColor whiteColor];
    config.threePartyKeyboard = NO;
    return config;
}
@end
